import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import mall from "@src/store/mall";
import location from "@src/store/location";
import {getDistance} from "@src/common/utils";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: mall,
    fields: ['curLocation', 'userLocation'],
    actions: ['initLocation', 'checkAuth']
  }, {
    store: location,
    actions: ['setAuth']
  }],
  properties: {
    store: {
      type: Object,
      value: {}
    },
    goodsDelivery: {
      type: Object,
      value: {},
      observer: "initDelivery"
    }
  },
  data: {
    locationInfo: "距离您4.6km",
    distance: null,
    delivery: null
  },
  observers: {
    'curLocation, store': function (curLocation, store){
      if (curLocation && store) {
        if (this.data.userLocation) {
          let distance = getDistance(this.data.userLocation.latitude, this.data.userLocation.longitude, store.latitude, store.longitude)
          this.setData({distance: distance})
        } else {
          let distance = getDistance(curLocation.latitude, curLocation.longitude, store.latitude, store.longitude)
          this.setData({distance: distance})
        }
      } else {
        this.setData({distance: null})
      }
    }
  },
  methods: {
    initDelivery(goodsDelivery) {
      if (!goodsDelivery || goodsDelivery.length ===0) {
        this.setData({delivery: null});
        return;
      }
      let delivery = null;
      for(let i = 0; i< goodsDelivery.length; i ++) {
        if (goodsDelivery[i].deliveryType === 'SELF_PICKUP') {
          delivery =  goodsDelivery[i];
          break
        }
      }
      this.setData({delivery: delivery});
    }
  }
});
